package com.ls.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.ls.system.entity.SysMenu;
import com.ls.system.mapper.SysMenuMapper;
import com.ls.system.service.SysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ls
 * @since 2025-04-06
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    // 获取树形菜单结构（仅可用菜单）
    @Override
    public List<SysMenu> getMenuTree(Integer parentId) {
        return  sysMenuMapper.selectList(new QueryWrapper<SysMenu>().eq("pid", parentId));
    }

    @Override
    public List<SysMenu> getMenusByUserId(Integer userId) {
        return this.baseMapper.getMenusByUserId(userId);
    }

    @Override
    public List<Integer> getAllSubMenuIds(Integer menuId) {
        // 1. 查询所有菜单数据（可缓存优化）
        List<SysMenu> allMenus = this.list();

        // 2. 递归查找所有子菜单ID（包含自身）
        List<Integer> menuIds = new ArrayList<>();
        menuIds.add(menuId); // 包含当前菜单
        findSubMenuIds(menuId, allMenus, menuIds);
        return menuIds;
    }

    // 递归查找子菜单ID
    private void findSubMenuIds(Integer parentId, List<SysMenu> allMenus, List<Integer> menuIds) {
        for (SysMenu menu : allMenus) {
            if (parentId.equals(menu.getPid())) { // pid为父菜单ID字段
                menuIds.add(menu.getId());
                findSubMenuIds(menu.getId(), allMenus, menuIds); // 递归查找子菜单
            }
        }
    }


    // 递归构建树形结构
    private List<SysMenu> buildTree(List<SysMenu> menus, Integer parentId) {
        List<SysMenu> tree = new ArrayList<>();
        for (SysMenu menu : menus) {
            if (menu.getPid().equals(parentId)) {
                menu.setChildren(buildTree(menus, menu.getId()));
                tree.add(menu);
            }
        }
        return tree;
    }
}
